package cn.iocoder.yudao.module.scrm.service.marketing.look;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.scrm.controller.admin.marketing.vo.look.MarketingLookPageReqVO;
import cn.iocoder.yudao.module.scrm.controller.admin.marketing.vo.look.MarketingLookSaveReqVO;
import cn.iocoder.yudao.module.scrm.dal.dataobject.marketing.MarketingLookDO;
import cn.iocoder.yudao.module.scrm.dal.mysql.marketing.MarketingLookMapper;
import cn.iocoder.yudao.module.system.api.permission.PermissionApi;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;


import cn.iocoder.yudao.framework.common.util.object.BeanUtils;


import java.util.Objects;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.iocoder.yudao.module.scrm.enums.ErrorCodeConstants.*;

/**
 * 营销浏览 Service 实现类
 *
 * @author admin
 */
@Service
@Validated
public class MarketingLookServiceImpl implements MarketingLookService {

    @Resource
    private MarketingLookMapper marketingLookMapper;

    @Resource
    private PermissionApi permissionApi;

    @Override
    public Integer createMarketingLook(MarketingLookSaveReqVO createReqVO) {
        // 插入
        MarketingLookDO marketingLook = BeanUtils.toBean(createReqVO, MarketingLookDO.class);
        marketingLookMapper.insert(marketingLook);
        // 返回
        return marketingLook.getId();
    }

    @Override
    public void updateMarketingLook(MarketingLookSaveReqVO updateReqVO) {
        // 校验存在
        validateMarketingLookExists(updateReqVO.getId());
        // 更新
        MarketingLookDO updateObj = BeanUtils.toBean(updateReqVO, MarketingLookDO.class);
        marketingLookMapper.updateById(updateObj);
    }

    @Override
    public void deleteMarketingLook(Integer id) {
        // 校验存在
        validateMarketingLookExists(id);
        // 删除
        marketingLookMapper.deleteById(id);
    }

    private void validateMarketingLookExists(Integer id) {
        if (marketingLookMapper.selectById(id) == null) {
            throw exception(MARKETING_LOOK_NOT_EXISTS);
        }
    }

    @Override
    public MarketingLookDO getMarketingLook(Integer id) {
        return marketingLookMapper.selectById(id);
    }

    @Override
    public PageResult<MarketingLookDO> getMarketingLookPage(MarketingLookPageReqVO pageReqVO) {
        if(!permissionApi.roleIsSuperAdmin(getLoginUserId()).getCheckedData()) {
            //用户id转成企业微信wxId进行查询
            pageReqVO.setCreator(Objects.requireNonNull(getLoginUserId()).toString());
        }
        return marketingLookMapper.selectPage(pageReqVO);
    }

}